﻿#include <QCoreApplication>
#include <QDebug>

// 通信设备接口类
class Device
{
public:
    virtual void write() = 0;
    virtual void read() = 0;
};

///
/// 具体的子类，网口通信类
///
class EthernetDevice : public Device
{
public:
    EthernetDevice()
    {
        qDebug()<<"EthernetDevice construct";
    }

    virtual ~EthernetDevice()
    {
        qDebug()<<"EthernetDevice disconstruct";
    }

    virtual void write()
    {
        qDebug()<<"EthernetDevice write";
    }

    virtual void read()
    {
        qDebug()<<"EthernetDevice read";
    }
};

///
/// 具体的子类，串口通信类
///
class UartDevice: public Device
{
public:
    UartDevice()
    {
        qDebug()<<"uartDevice construct";
    }

    virtual ~UartDevice()
    {
        qDebug()<<"uartDevice disconstruct";
    }

    virtual void write()
    {
        qDebug()<<"uartDevice write";
    }

    virtual void read()
    {
        qDebug()<<"uartDevice read";
    }
};


// 抽象模板工厂类
// 模板参数：AbstractDevice_t 设备抽象类
template <class AbstractDevice_t>
class AbstractFactory
{
public:
    virtual AbstractDevice_t *createDevice() = 0;
    virtual ~AbstractFactory() {}
};

// 具体模板工厂类
// 模板参数：AbstractDevice_t 设备抽象类，ConcreteDevice_t 设备具体类
template <class AbstractDevice_t, class ConcreteDevice_t>
class ConcreteFactory : public AbstractFactory<AbstractDevice_t>
{
public:
    AbstractDevice_t *createDevice()
    {
        return new ConcreteDevice_t();
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    //ConcreteFactory<Device, EthernetDevice> factory;
    ConcreteFactory<Device, UartDevice> factory;
    Device* dev = factory.createDevice();

    dev->write();
    dev->read();
    //。。。


    return a.exec();
}
